import 'package:flutter/material.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:provider/provider.dart';
import 'package:vega/constant/constant.dart';
import 'package:vega/page/home_view_model.dart';
import 'package:vega/repo/model/home_banner_model.dart';
import 'package:vega/repo/model/home_list_model.dart';
import 'package:vega/route/Routes.dart';
import 'package:vega/utils/common.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var model = HomeViewModel();

  @override
  void initState() {
    super.initState();
    model.initHomeList();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => model,
      builder: (context, widget) => Consumer<HomeViewModel>(
          builder: (context, value, child) => ListView.builder(
                itemCount: value.listData.length + 1,
                itemBuilder: (context, i) {
                  if (i == 0) {
                    return const Column(
                      children: [
                        _TopBar(),
                        _Banner(),
                        _LabelBar("我的追番", true),
                        _LabelBar("正在热播", true),
                        _LabelBar("新番时间表", true),
                        _TimelineTable(),
                      ],
                    );
                  } else {
                    final it = value.listData[i - 1];
                    return Column(
                      children: [
                        _LabelBar(it.label ?? "null", true,
                            margin: const EdgeInsets.only(
                                left: 10, top: 15, right: 10, bottom: 6)),
                        _AnimeTable(its: it.items),
                      ],
                    );
                  }
                },
              )),
    );

    return ListView(
      children: const [
        _TopBar(),
        _Banner(),
        _LabelBar("我的追番", true),
        _LabelBar("正在热播", true),
        _LabelBar("新番时间表", true),
        _TimelineTable(),
        _LabelBar("今日热播", true,
            margin: EdgeInsets.only(left: 10, top: 15, right: 10, bottom: 6)),
        // _AnimeTable(),
        // _LabelBar("大陆动漫", true),
        // _AnimeTable(),
        // _LabelBar("番组计划", true),
        // _AnimeTable(),
        // _LabelBar("剧场动画", true),
        // _AnimeTable(),
        // _LabelBar("剧集", true),
        // _AnimeTable(),
        // _LabelBar("电影", true),
        // _AnimeTable(),
      ],
    );
  }
}

class _LabelBar extends StatelessWidget {
  final String _label;
  final bool _hasMore;
  final EdgeInsetsGeometry? margin;

  const _LabelBar(this._label, this._hasMore, {this.margin, super.key});

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: margin ??
            const EdgeInsets.only(left: 10, top: 10, right: 10, bottom: 6),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              _label,
              style: const TextStyle(fontSize: 14, color: Colors.black87),
            ),
            InkWell(
              borderRadius: BorderRadius.circular(10),
              onTap: () => showSnack(context, "点击了“$_label”"),
              child: Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(width: 1, color: Colors.black26)),
                padding: const EdgeInsets.only(left: 4, right: 4),
                height: 20,
                child: const Text(
                  Constant.text_more,
                  style: TextStyle(fontSize: 12, color: Colors.black87),
                ),
              ),
            )
          ],
        ));
  }
}

class _TimelineTable extends StatelessWidget {
  const _TimelineTable();

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: 6,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, i) => Padding(
              padding:
                  const EdgeInsets.only(left: 12, right: 12, top: 6, bottom: 6),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.asset(
                      "${Constant.ASSETS_IMG}img_avatar.png",
                      width: 64,
                      height: 64,
                      fit: BoxFit.cover,
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.all(6),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          Constant.text_tips,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style:
                              TextStyle(fontSize: 15, color: Colors.pinkAccent),
                        ),
                        Text(
                          Constant.text_tips,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 12, color: Colors.black45),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ));
  }
}

class _AnimeTable extends StatelessWidget {
  List<Item> its = [];

  _AnimeTable({super.key, List<Item>? its}) {
    this.its = its ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        GridView.builder(
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 10,
              crossAxisSpacing: 10,
              childAspectRatio: 0.618,
            ),
            padding: const EdgeInsets.all(10),
            itemCount: its.length,
            itemBuilder: (context, i) => _itemCard(context, its[i]))
      ],
    );
  }

  Widget _itemCard(BuildContext context, Item it) {
    return InkWell(
      onTap: () => Navigator.of(context).pushNamed(RoutePath.play),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              child: ClipRRect(
            borderRadius: BorderRadius.circular(6.0),
            child: Image.network(it.coverUrl ?? "", fit: BoxFit.cover),
          )),
          const Divider(height: 6, color: Colors.transparent),
          const Text(
            Constant.text_tips,
            style: TextStyle(fontSize: 13, color: Colors.black87),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          const Divider(height: 4, color: Colors.transparent),
          const Text(
            Constant.text_tips,
            style: TextStyle(fontSize: 11, color: Colors.pinkAccent),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          )
        ],
      ),
    );
  }
}

class AnimeCard extends StatelessWidget {
  const AnimeCard({super.key});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => Navigator.of(context).pushNamed(RoutePath.play),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              child: ClipRRect(
            borderRadius: BorderRadius.circular(6.0),
            child: Image.asset("${Constant.ASSETS_IMG}img_banner.jpg",
                fit: BoxFit.cover),
          )),
          const Divider(height: 6, color: Colors.transparent),
          const Text(
            Constant.text_tips,
            style: TextStyle(fontSize: 13, color: Colors.black87),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          const Divider(height: 4, color: Colors.transparent),
          const Text(
            Constant.text_tips,
            style: TextStyle(fontSize: 11, color: Colors.pinkAccent),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          )
        ],
      ),
    );
  }
}

class _Banner extends StatefulWidget {
  const _Banner({super.key});

  @override
  State<StatefulWidget> createState() => _BannerState();

  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(left: 12, right: 12),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: AspectRatio(
            aspectRatio: 20.0 / 9,
            child: Image.asset(
              "${Constant.ASSETS_IMG}img_banner.jpg",
              fit: BoxFit.cover,
            ),
          ),
        ));
  }
}

class _BannerState extends State<_Banner> {
  final List<HomeBannerModel> banners = [];

  @override
  void initState() {
    super.initState();
    const mediaUrl0 =
        "https://c-ssl.duitang.com/uploads/blog/202209/08/20220908181446_5e6b5.png";
    const mediaUrl1 =
        "https://c-ssl.duitang.com/uploads/blog/202209/08/20220908181446_e4307.jpg";
    const mediaUrl2 =
        "https://c-ssl.duitang.com/uploads/blog/202209/08/20220908181446_c1028.jpg";
    const mediaUrl3 =
        "https://c-ssl.duitang.com/uploads/blog/202008/30/20200830225104_36f5c.jpg";

    banners.add(HomeBannerModel(mediaUrl: mediaUrl0));
    banners.add(HomeBannerModel(mediaUrl: mediaUrl1));
    banners.add(HomeBannerModel(mediaUrl: mediaUrl2));
    banners.add(HomeBannerModel(mediaUrl: mediaUrl3));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        height: 150,
        margin: EdgeInsets.only(left: 23, right: 23, top: 20),
        child: Swiper(
            indicatorLayout: PageIndicatorLayout.NONE,
            autoplayDelay: 5000,
            duration: 800,
            autoplay: true,
            pagination: SwiperPagination(
                margin: EdgeInsets.all(5),
                builder: DotSwiperPaginationBuilder(
                    size: 8,
                    activeColor: Colors.blueAccent,
                    color: Colors.grey)),
            // control: SwiperControl(size: 5.r),
            autoplayDisableOnInteraction: false,
            onTap: (int index) {},
            itemBuilder: (BuildContext context, int index) {
              return ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(5)),
                  child: Image.network(banners[index].mediaUrl ?? "",
                      fit: BoxFit.cover));
            },
            itemCount: banners.length));
  }
}

class _TopBar extends StatelessWidget {
  const _TopBar({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Padding(padding: MediaQuery.of(context).padding),
        SizedBox(
          height: 66.0,
          child: _searchBar(context),
        )
      ],
    );
  }

  Widget _searchBar(BuildContext context) {
    return Row(
      children: [
        const Expanded(
            flex: 1,
            child: CircleAvatar(
              backgroundColor: Colors.white,
              backgroundImage:
                  AssetImage("${Constant.ASSETS_IMG}img_avatar.png"),
            )),
        Expanded(
            flex: 5,
            child: GestureDetector(
              onTap: () => Navigator.of(context).pushNamed(RoutePath.search),
              child: Container(
                height: 28.0,
                decoration: const BoxDecoration(
                    shape: BoxShape.rectangle,
                    color: Color.fromARGB(0xff, 0xe0, 0xe0, 0xe0),
                    borderRadius: BorderRadius.all(Radius.circular(14.0))),
                child: const Padding(
                  padding: EdgeInsets.only(left: 8.0, right: 10.0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.search,
                        size: 16.0,
                      ),
                      Text(
                        "搜索你想看的吧~",
                        textAlign: TextAlign.start,
                        style: TextStyle(
                            fontSize: 12.0,
                            color: Color.fromARGB(0xff, 0x9e, 0x9e, 0x9e)),
                      ),
                    ],
                  ),
                ),
              ),
            )),
        const Padding(padding: EdgeInsets.only(left: 15.0)),
      ],
    );
  }
}
